import numpy

class Spike_train():
    """
    This object makes it easy to access data related to a spike train.  It has many
        classmethods for reading in from different formats.
    """
    def __init__(self, spike_times, time_offset=0.0, name=None):
        self.name = name
        self._spike_times = numpy.array(spike_times, dtype=numpy.float64)
        self.time_offset = time_offset
            
    @classmethod
    def from_binary(cls, binary_spikes, time_array=None, dt=None, **kwargs):
        """
        This is a way of creating a Spike_train object from an input which is
            made up of a time array, or a dt value and a binary array.
            time_array    = [0.1, 0.2, 0.3, 0.4, ...]
            binary_spikes = [  0,   1,   1,   0, ...]
            --alternatively--
            dt = 0.1
            binary_spikes = [  0,   1,   1,   0, ...]
        """
        # calculate the spike times
        if time_array:
            spike_time_array = [time_array[i] for i, spike in enumerate(binary_spikes) 
                                         if spike]
        else:
            spike_time_array = [i*dt for i, spike in enumerate(binary_spikes) if spike]
        return Spike_train(spike_time_array, **kwargs)

    @property
    def spike_times(self):
        return self._spike_times - self.time_offset

    @property
    def interspike_intervals(self):
        return self.spike_times[1:] - self.spike_times[:-1]
        
    
